<?php
/**
 * 按岗位导入 from hroa
* **/
apf_require_class('Oa_Job_Attendance_Abstract');
apf_require_class('Bll_Hr_OutInterface');
class Oa_Job_Attendance_SyncHroaJobInfo extends Oa_Job_Attendance_Abstract {
    /** 数据库写 **/
    private $writedb = 'attendance_master';
    private $is_init=0;//init

    public function run($params) {
        $time_start = time();
        $this->log("开始执行啦！".date('Y-m-d H:i:s'));

        $this->api = new Bll_Hr_OutInterface();
        $this->is_init = empty($params) ?  0 : 1;
        //同步部门信息
        $this->sync_department();
        $this->log('同步部门信息 End');

        $this->get_api_user_data();

        //同步人员信息
        $this->sync_user();
        $this->log('同步人员信息 End');
        //同步职位
        $this->sync_relation();
        $this->log('同步上下级关系 End');

        $time_end = time();
        $this->log('(End Job--'.date('Y-m-d H:i:s').')'.($time_end-$time_start).'seconds');
    }
    /**
     * 同步部门信息
     * @return mixed
     */
    private function sync_department(){
        /*$api_dep_url = $this->get_api_url('SearchDepartment');
        $dep_data = $this->get_data($api_dep_url);*/
        $dep_data = $this->api->search_department();

        if(empty($dep_data)){
            $this->log("同步部门信息失败");exit(1);
        }
        if($this->is_init){
            $del_sql = "delete from department where 1";
            $this->execute($del_sql,array(),$this->writedb);
        }

        $s_sql = "select * from department";
        $oa_department = $this->get_db_rows_assoc($s_sql, $this->writedb);
        if(empty($oa_department)){
            foreach($dep_data as $val){
                $dep_name=$val['bu_name'].$val['department_name'];
                $this->insert_department($val['department_id'],$dep_name,$val['city_name'],0);
            }
        }else{
            foreach($dep_data as $val){
                $dep_name=$val['bu_name'].$val['department_name'];
                if(isset($oa_department[$val['department_id']])){//部门存在
                    if($val['is_deleted']==1){
                        $u_sql = "update department set department_name = '{$dep_name}' where department_id = {$val['department_id']}";
                        $this->execute($u_sql,array(),$this->writedb);
                    }else{
                        $this->del_department($val['department_id']);
                    }
                }else{
                    $this->insert_department($val['department_id'],$dep_name,$val['city_name'],0);
                }
            }
        }
        $dep_data = null;
        unset($dep_data);
        return true;
    }

    private function insert_department($dep_id,$dep_name,$city_name,$is_del){
        $in_sql = "insert into department(department_id,department_name,kd_department_id,kd_company_id,city_name,is_del) values ({$dep_id},'{$dep_name}','','','{$city_name}',{$is_del})";
        $this->execute($in_sql,array(),$this->writedb);
    }
    private function del_department($dep_id){
        $u_sql = "update department set is_del=1 where department_id = {$dep_id}";
        $this->execute($u_sql,array(),$this->writedb);
    }
    /**
     * 同步职位
     */
    public function sync_relation(){

        if($this->is_init){
            //$del_sql = "delete from org_relation where 1";
            //$this->execute($del_sql,array(),$this->writedb);
        }
        $sql = "SELECT * FROM org_relation where 1";
        $has_org = $this->get_db_rows_assoc($sql,$this->writedb);
        $uids_relation=array();
        foreach($has_org as $val){//查询已存在的关系，方便检测是否需要删除关系
            $uids_relation[$val['user_id']] = $val['id'];
        }

        $api_user_rel_url = $this->get_api_url('SearchRelation');

        foreach($this->user_data as $val){
            if($val['job_status']==2){//只对在职用户进行修改，离职员工关系直接删除
                if(isset($uids_relation[$val['user_id']])){
                    $del_sql = "DELETE FROM org_relation WHERE user_id={$val['user_id']} ";
                    $this->execute($del_sql,array(),$this->writedb);
                }
            }else{
                //$parent_list = $this->get_data($api_user_rel_url.'&uids='.$val['user_id']);
                $parent_list = $this->api->get_user_relation(array($val['user_id']));
                $this->_update_user_relation($val['user_id'],$parent_list[$val['user_id']]);
            }
        }
    }

    /**
     * 更新用户的上级关系
     * @param int $uid
     * @param array $parent_list array(0=>12,1=>23)
     * @return boolean
     */
    private function _update_user_relation($uid,$parent_list){
        $sql = "SELECT * FROM org_relation where user_id={$uid}";
        $has = $this->get_db_rows_assoc($sql,$this->writedb);

        if(empty($has)){//没有找到这个人的上级关系
            if(empty($parent_list)){// mike没有上级
                return false;
            }
            $i=1;
            foreach($parent_list as $val){
                $indata = array(
                        'user_id'=>$uid,
                        'superior_id'=>$val,
                        'level'=>$i
                        );
                $this->_update_relation($indata,1);
                $i++;
            }
        }else{
            $old_parent = $parent_list;
            foreach($has as $val){
                if(!in_array($val['superior_id'],$parent_list)){
                    //delete
                    $del_sql = "DELETE FROM org_relation WHERE id={$val['id']} ";
                    $this->execute($del_sql,array(),$this->writedb);
                }else{
                    $level = array_search($val['superior_id'],$parent_list);
                    unset($old_parent[$level]);//为了后面新增上级关系
                    $level +=1;//parent_list索引从0开始的
                    if($level !=$val['level']){//上级关系还在存在，但level级数不同,level级数相同的不处理
                        //update level
                        $update = array(
                            'level'=>$level
                        );
                        $this->_update_relation($update,0,$val['id']);
                    }
                }
            }
            if(!empty($old_parent)){//原上级关系 从 1 2 5 变为1 3 5时 3会在这里处理
                foreach($old_parent as $k=>$val){
                    //insert level=$k+1;
                    $indata = array(
                            'user_id'=>$uid,
                            'superior_id'=>$val,
                            'level'=>$k+1
                    );
                    $this->_update_relation($indata,1);
                }
            }
        }
    }
    /**
     * 插入和更新数据表
     * @param unknown_type $indata
     * @param unknown_type $up
     * @param unknown_type $id
     */
    private function _update_relation($indata,$up=0,$id=0){
        $sql = $this->_implode_field_value($indata);
        if($up){
            $sql = "INSERT INTO org_relation SET $sql";
        }else{
            $sql = "UPDATE org_relation SET $sql WHERE id={$id}";
        }
        $this->execute($sql,array(),$this->writedb);
    }
    /**
     * 同步 用户数据
     */
    public function sync_user(){
        $s_sql = "select user_id,kd_em_id,job_status from user_info";
        $oa_userinfo_data = $this->get_db_rows_assoc($s_sql, $this->writedb);

        $api_one_user = $this->get_api_url('GetUserByUids');

        foreach($this->user_data as $val){
            //api获取员工信息
            //$user_info = $this->get_data($api_one_user."&uids=".$val['user_id']);
            $user_info = $this->api->get_user_by_ids(array($val['user_id']));
            if($user_info[$val['user_id']]['department_name']=='' && $user_info[$val['user_id']]['job_status']==1){

            }
            if(!isset($oa_userinfo_data[$val['user_id']])){
                //insert
                $this->_update_user_info($user_info[$val['user_id']],1);
            }else{
                //update
                if($user_info[$val['user_id']]['job_status']==2 && $oa_userinfo_data[$val['user_id']]['job_status']=='离职'){
                    //如果两边用户都离职了， 不用更新数据了
                    continue;
                }
                $this->_update_user_info($user_info[$val['user_id']]);
            }
        }
        $this->log("Sync User Information Done");

    }

    /**
     * insert/update 数据
     * @param unknown_type $data
     * @param unknown_type $up
     */
    private function _update_user_info($data,$up=0){
        $enter_date = date('Y-m-d H:i:s',strtotime($data['enter_date']));
        $indue_date = empty($data['indue_date']) ? '0000-00-00 00:00:00' : date('Y-m-d H:i:s',strtotime($data['indue_date']));
        $dimission_date = empty($data['dimission_date']) ? '0000-00-00 00:00:00' : date('Y-m-d H:i:s',strtotime($data['dimission_date']));
        if($data['leaving_type']==3){
            return false;//未来报到的不管
            $dimission_date=date('Y-m-d 00:00:00',strtotime($data['enter_date']));
        }
        $indata = array(
                'user_id'=>$data['user_id'],
                'name'=>$data['name'],
                'code'=>$data['code'],
                'email'=>$data['email'],
                'english_name'=>$data['english_name'],
                'sex'=>$data['sex'],
                'telphone'=>$data['telphone'],
                'mobile'=>$data['mobile'],
                'enter_date'=>$enter_date,
                'indue_date'=>$indue_date,
                'dimission_date'=>$dimission_date,
                'employees_type'=>$this->get_all_user_type($data['employees_type']),
                'job_status'=>$this->job_status($data['job_status']),

                'job_name'=>$data['job_name'],
                'position_name'=>$data['job_name'],
                'department_id'=>$data['department_id'],
                'department_name'=>$data['department_name'],
                'city_name'=>$data['city_name'],
                'group_name'=>$data['bu_name'],
                'sub_company_name'=>$data['city_name'],
                'superior_code'=>$data['superior_code'],
            );
        $sql = $this->_implode_field_value($indata);
        if($up){
            $sql = "INSERT INTO user_info SET $sql";
            $sql_role="INSERT INTO user_role (`user_id`, `role_id`) VALUES ('".$data['user_id']."', '5')";
            $this->execute($sql_role,array(),$this->writedb);
        }else{
            if($data['job_status']==2){
                $sql = "job_status='离职',dimission_date='".$dimission_date."'";
            }
            $sql = "UPDATE user_info SET $sql WHERE user_id={$data['user_id']}";
        }
        $this->execute($sql,array(),$this->writedb);
    }
    /**
     * 组合数据为update 条件
     * @param array $array
     * @param string $glue
     * @return string
     */
    private function _implode_field_value($array, $glue = ',') {
        $sql = $comma = '';
        foreach ($array as $k => $v) {
            $sql .= $comma."`$k`='$v'";
            $comma = $glue;
        }
        return $sql;
    }

    private $user_data = array();

    private function get_api_user_data(){
        if(empty($this->user_data)){
            //$api_user_url = $this->get_api_url('GetAllUser');
            //$this->user_data = $this->get_data($api_user_url);
            $this->user_data = $this->api->search_all_user();
        }
    }
    /**
     * 员工类型
     * @param unknown_type $type
     */
    private function get_all_user_type($type){
        $list= array(
                3 => array('type_id'=>3,'type_name'=>'实习员工'),
                1 => array('type_id'=>1,'type_name'=>'试用员工'),
                2 => array('type_id'=>2,'type_name'=>'正式员工'),
                4 => array('type_id'=>4,'type_name'=>'兼职员工'),
                5 => array('type_id'=>5,'type_name'=>'临时员工'),
        );
        return $list[$type]['type_name'];
    }
    private function job_status($status){
        $list =array(1=>'在职',2=>'离职');
        return $list[$status];
    }
    /**
     * build_url
     * @param unknown_type $type
     * @param unknown_type $params
     * @return unknown
     */
    private function get_api_url($type,$params=array()){
        $url = APF::get_instance()->get_config('user_api_domain');
        $url .='type='.$type;
        if(!empty($params)){
            foreach($params as $key=> $val){
                $url .= "&{$key}=";
                if(is_array($val)){
                    $url .= implode(',',$val);
                }else{
                    $url .= $val;
                }
            }
        }
        return $url;
    }

    private function get_data($api_url){
        apf_require_class('APF_Http_Client_Factory');
        $objCURL = APF_Http_Client_Factory::get_instance()->get_curl();
        $objCURL->set_url($api_url);
        $bolResult = $objCURL->execute();
        $strResource = $objCURL->get_response_text();
        $data = json_decode($strResource, true);
        return $data;
    }
}
